package com.chen.club.gateway.auth;

import cn.dev33.satoken.stp.StpInterface;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.chen.club.gateway.entity.AuthPermission;
import com.chen.club.gateway.entity.AuthRole;
import com.chen.club.gateway.redis.RedisUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 自定义权限验证接口扩展
 */
@Component
public class StpInterfaceImpl implements StpInterface {
    @Resource
    private RedisUtil redisUtil;

    private final String authPermissionPrefix = "auth.permission";

    private final String authRolePrefix = "auth.role";



    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        return getAuth(loginId.toString(), authPermissionPrefix);
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        return getAuth(loginId.toString(), authRolePrefix);
    }

    /**
     * 获取信息
     * @param loginId id
     * @param prefix 权限标识
     * @return authList
     */
    public List<String> getAuth(String loginId, String prefix) {
        String authKey = redisUtil.buildKey(authPermissionPrefix, loginId.toString());
        //从redis中获取登录用户的角色信息
        String authValue = redisUtil.get(authKey);
        //判断角色信息是否为空
        if (StringUtils.isBlank(authValue)){
            return Collections.emptyList();
        }
        List<String> authList = new LinkedList<>();
        //判断权限标识
        if (authRolePrefix.equals(prefix)) {
            //获取
            List<AuthRole> roleList = new Gson().fromJson(authValue, new TypeToken<List<AuthRole>>() {
            }.getType());
            //获取角色的key
            authList = roleList.stream()
                    .map(AuthRole::getRoleKey)
                    .collect(Collectors.toList());
        } else if (authPermissionPrefix.equals(prefix)) {
            //获取权限信息
            List<AuthPermission> permissionList = new Gson().fromJson(authValue, new TypeToken<List<AuthPermission>>() {
            }.getType());
            //获取权限key
            authList = permissionList.stream()
                    .map(AuthPermission::getPermissionKey)
                    .collect(Collectors.toList());
        }
        return authList;
    }


}
